import json
import Ui_QtInterface
import sys
import os
import opennsfw2 as n2
import time
import draw

from PyQt5 import QtCore
from PyQt5.QtCore import QThread, pyqtSignal, QMutex
from PyQt5.QtWidgets import QApplication, QDialog, QFileDialog

Lock_Mutex = QMutex()
Selected_File = ''
Selected_DataFile = ''

# class Draw(QThread):
#     callback_msg = pyqtSignal(str)
#     # btns = pyqtSignal(bool)
#     def __init__(self) -> None:
#         super().__init__()
    
#     def run(self) -> None:

#         else:
#             self.callback_msg.emit('程序正忙。')


class Check(QThread):
    # btns = pyqtSignal(bool)
    callback_msg = pyqtSignal(str)
    callback_path = pyqtSignal(str)
    def __init__(self):
        super().__init__()
    
    def run(self) -> None:
        global Selected_File
        if Lock_Mutex.tryLock(0):
            seconds, probabilities = n2.predict_video_frames(Selected_File)
            self.callback_msg.emit('视频解析成功。')
            temp_data=[]
            for _ in range(len(seconds)):
                temp_data.append({'second':float(seconds[_]), 'possibility':float(probabilities[_])})
            filename_ = Selected_File.rsplit('.', 1)[0].strip()+'_'+str(int(time.time()))+'.json'
            with open(filename_, 'w', encoding='utf-8') as f:
                json.dump(temp_data, f, indent=2, ensure_ascii=False)
            Lock_Mutex.unlock()
            self.callback_msg.emit('文件保存于'+filename_)
            self.callback_path.emit(filename_)
            # self.btns.emit(True)
        else:
            self.callback_msg.emit('当前线程忙。')

class MainDialog(QDialog):
    def __init__(self, parent=None):
        global Selected_File, Selected_DataFile
        super(QDialog, self).__init__(parent)
        self.ui = Ui_QtInterface.Ui_NSFWsoftware()
        self.ui.setupUi(self)
        self.ui.Check.setEnabled(False)
        self.ui.Check_2.setEnabled(False)
        self.CheckThread = Check()
        self.CheckThread.callback_msg.connect(self.push_message)
        # self.CheckThread.btns.connect(self.buttons_control)
        self.CheckThread.callback_path.connect(self.set_datapath)

        # self.DrawThread = Draw()
        # self.DrawThread.callback_msg.connect(self.push_message)

        Selected_File = ''
        Selected_DataFile = ''

    def browse_data(self):
        file_choose = QFileDialog.getOpenFileName(self, caption="选取数据文件",
                                                    directory=os.getcwd(),
                                                    filter="JSON数据档案 (*.json);;All Files (*)")
        self.set_datapath(file_choose[0])


    def browse(self):
        file_choose = QFileDialog.getOpenFileName(self, caption="选取一个视频",
                                                    directory=os.getcwd(),
                                                    filter="AVI Files (*.avi);;MP4 Files (*.mp4);;FLV Files (*.flv);;WMV Files (*.wmv);;All Files (*)")
        self.set_filepath(file_choose[0])

    def check(self):
        global Selected_File
        self.ui.Check.setEnabled(False)
        if os.path.isfile(Selected_File):
            self.CheckThread.start()
            self.ui.Hints.setText('文件存在, 尝试启动程序.')
        else:
            self.ui.Hints.setText('选择的文件不正确!')
        self.ui.Check.setEnabled(True)

    def draw(self):
        global Selected_DataFile
        self.ui.Check_2.setEnabled(False)
        if os.path.isfile(Selected_DataFile):
            # self.DrawThread.start()
            self.push_message('文件存在, 尝试绘图')

            if Lock_Mutex.tryLock(0):
                with open(Selected_DataFile, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                title = Selected_DataFile.rsplit('/', 1)[-1]

                drawer = draw.Draw(data, title)
                drawer.draw_box(self.ui.spinBox.value())

                Lock_Mutex.unlock()
        self.ui.Check_2.setEnabled(True)

    # def buttons_control(self, state: bool):
    #     self.ui.Check.setEnabled(state)
    #     self.ui.Browse.setEnabled(state)
    #     self.ui.Check_2.setEnabled(state)
    #     self.ui.Browse_2.setEnabled(state)
    
    def push_message(self, string):
        self.ui.Hints.setText(string)
    
    def set_filepath(self, string):
        global Selected_File
        Selected_File = string
        self.ui.FilePath.setText(string)
        if os.path.isfile(Selected_File):
            self.ui.Check.setEnabled(True)
        else:
            self.ui.Check.setEnabled(False)

    def set_datapath(self, string):
        global Selected_DataFile
        Selected_DataFile = string
        self.ui.FilePath_2.setText(string)
        if os.path.isfile(Selected_DataFile):
            self.ui.Check_2.setEnabled(True)
        else:
            self.ui.Check_2.setEnabled(False)

if __name__ == '__main__':
    myapp = QApplication(sys.argv)
    myDlg = MainDialog()
    myDlg.show()
    sys.exit(myapp.exec_())